package net.jueb.frameworkDemo.orm.redis.queue.unPersistent;

import java.util.Scanner;

import org.apache.commons.lang.RandomStringUtils;

import net.jueb.frameworkDemo.orm.redis.queue.Constants;
import redis.clients.jedis.JedisPubSub;

public class PubSubTestMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		//消息发布者
		final PubClient pubClient = new PubClient(Constants.host, Constants.port);
		final String channel = "test-channel";
		final String channel2 = "test-channel2";
		Thread pubThread = new Thread(new Runnable() {
			@Override
			public void run() {
				int i=0;
				while(i < 10)
				{
					String message = RandomStringUtils.random(6, true, true);//apache-commons
					pubClient.pub(channel, message);
					pubClient.pub(channel2, message);
					i++;
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
					}
				}
				pubClient.close(channel);
			}
		});
		pubThread.start();
		Thread.sleep(2000);
		//消息订阅者
		Thread subThread = new Thread(new Runnable() {
			@Override
			public void run() {
				try{
					SubClient subClient = new SubClient(Constants.host, Constants.port);
					JedisPubSub listener = new PrintListener();
					//在API级别，此处为轮询操作，直到unsubscribe调用，才会返回
					subClient.sub(channel,listener);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
		Thread subThread2 = new Thread(new Runnable() {
			@Override
			public void run() {
				try{
					SubClient subClient = new SubClient(Constants.host, Constants.port);
					JedisPubSub listener = new PrintListener();
					//在API级别，此处为轮询操作，直到unsubscribe调用，才会返回
					subClient.sub(channel,listener);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
		subThread.start();
		subThread2.start();
		new Scanner(System.in).nextLine();
	}
}